package com.example.movie.data.user.model

import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import cn.forward.androids.utils.ThreadUtil
import com.example.movie.R
import com.example.movie.common.constants.LoadingState
import com.example.movie.common.model.RequestResult
import com.example.movie.common.model.Result
import com.example.movie.data.user.login.model.LoggedInUser
import okhttp3.RequestBody

class UserInfoViewModel(private val repository: UserRepository) : ViewModel() {

    private val _userInfo = MutableLiveData<RequestResult<LoggedInUser>>()
    val userInfo: MutableLiveData<RequestResult<LoggedInUser>>
        get() = _userInfo

    private val _saveState = MutableLiveData<RequestResult<Boolean>>()
    val saveState: MutableLiveData<RequestResult<Boolean>>
        get() = _saveState


    fun loadUserInfo() {
        var result: Result<LoggedInUser>? = null;
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    if (result is Result.Success) {
                        _userInfo.value = RequestResult(success = (result as Result.Success<LoggedInUser>).data)
                    } else {
                        _userInfo.value = RequestResult(error = R.string.request_fail)
                    }
                }
            }

        }

        ThreadUtil.getInstance().execute {
            result = repository.loadUserInfo()
            val message = Message()
            message.what = LoadingState.OK
            handler.sendMessage(message)
        }
    }


    fun updateUser(user: LoggedInUser, headImage: RequestBody?) {
        var result: Result<Boolean>? = null;
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    if (result is Result.Success) {
                        _saveState.value = RequestResult(success = true)
                    } else {
                        _saveState.value = RequestResult(error = R.string.request_fail)
                    }
                }
            }

        }

        ThreadUtil.getInstance().execute {
            result = repository.updateUser(user,headImage)
            val message = Message()
            message.what = LoadingState.OK
            handler.sendMessage(message)
        }

    }




}